package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.utils.UserContext;
import com.jzo2o.customer.mapper.BankAccountMapper;
import com.jzo2o.customer.model.domain.BankAccount;
import com.jzo2o.customer.model.dto.request.BankAccountUpsertReqDTO;
import com.jzo2o.customer.model.dto.response.BankAccountResDTO;
import com.jzo2o.customer.service.IBankAccountService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
@Slf4j
public class BankAccountServiceImpl extends ServiceImpl<BankAccountMapper,BankAccount> implements IBankAccountService {

    @Override
    @Transactional
    public BankAccountResDTO add(BankAccountUpsertReqDTO bankAccountUpsertReqDTO) {
        Long currentUserId = UserContext.currentUserId();

        // 判断是新增还是修改
        BankAccount existingAccount = this.getById(currentUserId);

        BankAccount bankAccount = BeanUtil.toBean(bankAccountUpsertReqDTO, BankAccount.class);
        bankAccount.setId(currentUserId);

        if (existingAccount == null) {
            // 新增操作
            bankAccount.setCreateTime(LocalDateTime.now());
            log.info("新增银行账户，用户ID: {}", currentUserId);
        } else {
            // 修改操作
            bankAccount.setCreateTime(existingAccount.getCreateTime()); // 保留原创建时间
            bankAccount.setUpdateTime(LocalDateTime.now()); // 设置更新时间
            log.info("更新银行账户，用户ID: {}", currentUserId);
        }

        this.saveOrUpdate(bankAccount);
        return BeanUtil.toBean(bankAccount, BankAccountResDTO.class);
    }

    @Override
    @Transactional
    public BankAccountResDTO addOrUpdate(BankAccountUpsertReqDTO bankAccountUpsertReqDTO) {
        Long currentUserId = UserContext.currentUserId();

        // 判断是新增还是修改
        BankAccount existingAccount = this.getById(currentUserId);

        BankAccount bankAccount = BeanUtil.toBean(bankAccountUpsertReqDTO, BankAccount.class);
        bankAccount.setId(currentUserId);

        if (existingAccount == null) {
            // 新增操作
            bankAccount.setCreateTime(LocalDateTime.now());
            log.info("新增银行账户，用户ID: {}", currentUserId);
        } else {
            // 修改操作
            bankAccount.setCreateTime(existingAccount.getCreateTime()); // 保留原创建时间
            bankAccount.setUpdateTime(LocalDateTime.now()); // 设置更新时间
            log.info("更新银行账户，用户ID: {}", currentUserId);
        }

        this.saveOrUpdate(bankAccount);
        return BeanUtil.toBean(bankAccount, BankAccountResDTO.class);
    }
}
